package com.example.demo.controller;

import com.example.demo.utils.Base64;
import com.example.demo.utils.PassToken;
import com.example.demo.utils.ResponseResult;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Base64Utils;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class CodeController {
  @Resource(name = "captchaProducer")
    private Producer captchaProducer;
  private String captchaType;
  @Autowired
  private RedisTemplate redisTemplate;

  @PassToken
    @GetMapping("/getCheckCode")
    public ResponseResult getCheckCode(HttpServletResponse response){
      String uuid= UUID.randomUUID()+"";
      String verifykey="captcha_codes:"+uuid;
      String capStr=null,code=null;
      BufferedImage image=null;
      capStr =code=captchaProducer.createText();
      image=captchaProducer.createImage(capStr);
      redisTemplate.opsForValue().set(verifykey,code,2, TimeUnit.MINUTES);
      FastByteArrayOutputStream os=new FastByteArrayOutputStream();
      try {
          ImageIO.write(image,"jpg",os);
      }
      catch (IOException e){
          return ResponseResult.createByFail(500,"获取验证码失败");
      }
      Map<String,Object> map=new HashMap<>();
      map.put("uuid",uuid);
      map.put("img", Base64.encode(os.toByteArray()));
      return ResponseResult.createBySuccess(200,map,"获取成功");
  }

}
